package com.fysports.framework.render;

import com.jfinal.log.Log;
import com.jfinal.render.FreeMarkerRender;
import com.jfinal.render.IMainRenderFactory;
import com.jfinal.render.Render;
import com.jfinal.render.RenderException;


/**
 * 重写Jfinal中自带的FreemarkerFactory和Render，为了统计渲染时间
 * Created by konbluesky
 * Date : 14-9-12 下午7:25
 * Project : JdmData_WebServer
 */
public class MainRenderFactory implements IMainRenderFactory {
    private static Log logger = Log.getLog(MainRenderFactory.class);
    /*request 中存放的 KEY*/
    public static final String renderTimeKey = "fmk_render_Time";
    public static final String renderFlag = "fmk_render_Flag";
    public static final String RENDER_ERROR_EXP = "render_error_exp";     //存放异常 key
    public final static String FTL_SUCCESS = "1";
    public final static String FTL_FAIL = "0";
    public final static String JSON_SUCCESS = "3";
    public final static String JSON_FAIL = "2";
    public final static String JSON_ERROR = "4";


    @Override public Render getRender(String view) {
        return new TimerFreemarkRender(view);
    }


    @Override public String getViewExtension() {
        return ".html";
    }


    public class TimerFreemarkRender extends FreeMarkerRender {
        public TimerFreemarkRender(String view) {
            super(view);
        }


        @Override public void render() {
            long start = System.currentTimeMillis();
            String flag = FTL_FAIL;
            try {
                super.render();
                flag = FTL_SUCCESS;
            }
            catch (Exception e) {
                logger.error("渲染失败:", e);
                throw new RenderException(e);
                //将异常信息写入request
                //                request.setAttribute(RENDER_ERROR_EXP,e);
            }
            long end = System.currentTimeMillis();
            long renderTime = end - start;
            //成功标识
            request.setAttribute(MainRenderFactory.renderFlag, flag);
            //渲染时间
            request.setAttribute(MainRenderFactory.renderTimeKey, renderTime);
        }
    }
}
